﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Unity.InterceptionExtension;
using System.Configuration;
using System.Transactions;

namespace Artech.PetShop.Common
{
   public class AuditCallHandler:ICallHandler
    {
       private static DbHelper dbHelper = new DbHelper(ConfigurationManager.AppSettings["auditDb"]);

       public string Operation
       { get; private set; }

       public AuditCallHandler(string operation)
       {
           if (string.IsNullOrEmpty(operation))
           {
               throw new ArgumentNullException("operation");
           }
           this.Operation = operation;
       }

        #region ICallHandler Members

        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            IMethodReturn methodReturn = getNext()(input, getNext);
            if (methodReturn.Exception != null)
            {
                return methodReturn;
            }

            try
            {
                this.Audit(this.Operation);
                return methodReturn;
            }
            catch (Exception ex)
            {
                return input.CreateExceptionMethodReturn(ex);
            }
        }

        private void Audit(string operation)
        {
            string procedureName = "P_AUDIT_INSERT";
            Dictionary<string, object> parameters = new Dictionary<string, object>();
            parameters.Add("p_transaction_id", Transaction.Current.TransactionInformation.LocalIdentifier);
            parameters.Add("p_operation", operation);
            parameters.Add("p_operator", ApplicationContext.Current.UserName);
            dbHelper.ExecuteNonQuery(procedureName, parameters);
        }

        public int Order
        {get;set;}

        #endregion
    }
}
